Page({
  data: {
    breathHue: 0,
    breathSaturation: 100,
    breathLightness: 50,
    brightness: 100,
    speed: 60,
    breathColor: 'hsl(0,100%,50%)',
    showSlider: true,
    showBackBtn: true,
    hideTimer: null,
    breathTimer: null
  },
  onLoad(query) {
    this.setData({
      breathHue: Number(query.hue) || 0,
      breathSaturation: Number(query.saturation) || 100,
      breathLightness: Number(query.lightness) || 50,
      brightness: Number(query.brightness) || 100
    });
    this.updateBreathColor();
    this.startBreath();
    this.startAutoHide();
  },
  startBreath() {
    if (this.data.breathTimer) clearInterval(this.data.breathTimer);
    let t = 0;
    const { breathSaturation, breathLightness, speed } = this.data;
    const interval = Math.max(20, 220 - speed);
    this.data.breathTimer = setInterval(() => {
      t += 1;
      const hue = (this.data.breathHue + t * 2) % 360;
      const color = `hsl(${hue},${breathSaturation}%,${breathLightness}%)`;
      this.setData({ breathColor: color });
    }, interval);
  },
  updateBreathColor() {
    const { breathHue, breathSaturation, breathLightness } = this.data;
    const color = `hsl(${breathHue},${breathSaturation}%,${breathLightness}%)`;
    this.setData({ breathColor: color });
  },
  startAutoHide() {
    if (this.data.hideTimer) clearTimeout(this.data.hideTimer);
    this.data.hideTimer = setTimeout(() => {
      this.setData({ showSlider: false, showBackBtn: false });
    }, 1000);
  },
  toggleSlider(e) {
    if (e && e.target && e.target.dataset && e.target.dataset.btn) return;
    if (this.data.hideTimer) clearTimeout(this.data.hideTimer);
    this.setData({ showSlider: true, showBackBtn: true });
    this.startAutoHide();
  },
  onSpeedChange(e) {
    this.setData({ speed: e.detail.value });
    this.startBreath();
  },
  onSpeedChanging(e) {
    this.setData({ speed: e.detail.value });
    this.startBreath();
  },
  onBrightnessChanging(e) {
    this.setData({ brightness: e.detail.value });
    if (this.data.hideTimer) clearTimeout(this.data.hideTimer);
    this.startAutoHide();
  },
  onBrightnessChange(e) {
    this.setData({ brightness: e.detail.value });
  },
  updateBreathColorAndRestart() {
    const { breathHue, breathSaturation, breathLightness } = this.data;
    const color = `hsl(${breathHue},${breathSaturation}%,${breathLightness}%)`;
    this.setData({ breathColor: color });
    this.startBreath();
  },
  goBack() {
    wx.navigateBack();
  },
  onUnload() {
    if (this.data.hideTimer) clearTimeout(this.data.hideTimer);
    if (this.data.breathTimer) clearInterval(this.data.breathTimer);
  }
}); 